<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Leaflet customLayer-canvas 1.4.0</title>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.4.0/dist/leaflet.css"/>
  <script src="https://unpkg.com/leaflet@1.4.0/dist/leaflet.js"></script>
  <style>
    body {
      margin: 0;
    }
    #map {
      width: 100vw;
      height: 100vh;
    }
  </style>
</head>
<body>
<div id="map"></div>
<div width="500" height="800" style="background: #000;"></div>
<script src="../dist/Leaflet.CustomLayer.js"></script>

<script src="./data/citys.js" charset="utf-8"></script>
<script>
  var map = L.map("map", {
    zoomAnimation: true
  }).setView([39.910088, 116.401601], 4);

  L.tileLayer("https://{s}.tiles.mapbox.com/v4/mapbox.dark/{z}/{x}/{y}@2x.png?access_token=pk.eyJ1IjoiZ2xlYWZsZXQiLCJhIjoiY2lxdWxoODl0MDA0M2h4bTNlZ2I1Z3gycyJ9.vrEWCC2nwsGfAYKZ7c4HZA")
    .addTo(map);

  var data = citys; // data loaded from city.js

  var resizeContainer = function() {
    var canvas = this.getContainer();
    var m = L.Browser.retina ? 2 : 1;

    var size = this._bounds.getSize();//resize

    var padding = this._padding;
    canvas.width = m * size.x;
    canvas.height = m * size.y;
    canvas.style.width = size.x + "px";
    canvas.style.height = size.y + "px";

    var ctx = canvas.getContext("2d");

    if (L.Browser.retina) {
      ctx.scale(m, m);
    }
    ctx.translate(padding.x, padding.y);

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    return ctx;
  };

  var canvasLayer = L.customLayer({
    container: document.createElement("canvas"),
    padding: 0.1,
    zooms: [0, 18],
    opacity: 1,
    visible: true,
    zIndex: 120,
    alwaysRender: true
  });

  canvasLayer.on("layer-beforemount", function() {
    console.log("layer-beforemount");
  });

  canvasLayer.on("layer-mounted", function() {
    console.log("layer-mounted");
  });

  canvasLayer.on("layer-render", function() {
    console.log("layer-render");

    var ctx = resizeContainer.bind(this)();
    ctx.fillStyle = "rgba(255,116,0, 0.5)";

    var bounds = map.getBounds();

    for (var i = 0; i < data.length; i++) {
      var d = data[i].latlng;
      if (bounds.contains([d[0], d[1]])) {
        dot = map.latLngToContainerPoint([d[0], d[1]]);
        ctx.beginPath();
        ctx.arc(dot.x, dot.y, 3, 0, Math.PI * 2);
        ctx.fill();
        ctx.closePath();
      }
    }
  });

  canvasLayer.on("layer-beforedestroy", function() {
    console.log("layer-beforedestroy");
  });

  canvasLayer.on("layer-destroyed", function() {
    console.log("layer-destroyed");
  });

  canvasLayer.addTo(map);
</script>
</body>
</html>
